// pages/orderDetails/orderDetails.js
var app = getApp();
const Format = require("../../utils/time.js");
var clickCount = 0; // 点击第三方票券的次数
var QR = require("../../utils/qrcode.js");
var getTicketList = function(that, eventId, type) {
    app.getApi.getProducts("POST", {
        pageNumber: that.data.ftIndex,
        type: type,
        pageSize: 5,
        orderHeadId: that.data.items.id,
        // unionId: app.globalData.unionId,
        // eventId: eventId,
        method: "opg.ticketListGetByOrder.ticket",
    }).then(data => {
        var list = that.data.codeList;
        var size = that.data.size;
        if (data.data.result.length > 0) {
            for (let i = 0; i < data.data.result.length; i++) {
                // let dates = data.data.result[i].startTimeStr;
                // let times = dates.substring(5, 7) + "/" + dates.substring(8, 10);
                // data.data.result[i].startTimeStr = times
                that.createQrCode(data.data.result[i].number, "mycanvas" + i, size.w, size.h);
                list.push(data.data.result[i])
            }
        }

        that.setData({
            codeList: list,

        })
        that.setData({
            totalCount: data.data.totalCount,

        })
        that.Count()
    })
}
Page({

    /**
     * 页面的初始数据
     */
    data: {
        isChinese: wx.getStorageSync("isChinese"),
        totalCount: 0,
        ftIndex: 1,
        loadMore: true,
        codeShow: false, //是否查看票券
        codeList: [],
        opgCode: "",
        size: {},
        thirdparty: true //第三方票券显示
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        var that = this
        var size = this.setCanvasSize()
        that.setData({
            isChinese: wx.getStorageSync("isChinese"),
            size: size
        })
        wx.setNavigationBarTitle({
            title: that.data.isChinese ? "订单详情" : "Order info"
        })
        app.getApi.getProducts("POST", {
            id: options.id,
            method: "opg.orderHead.get"
        }).then(data => {

            let submitTime = parseInt(data.data.orderHead.submitTime)
            var o = {
                "y": new Date(submitTime).getFullYear(),
                "M": new Date(submitTime).getMonth() + 1 >= 10 ? new Date(submitTime).getMonth() + 1 : '0' + String(new Date(submitTime).getMonth() + 1), //月份 
                "d": new Date(submitTime).getDate() >= 10 ? new Date(submitTime).getDate() : '0' + String(new Date(submitTime).getDate()), //日 
                "h": new Date(submitTime).getHours() >= 10 ? new Date(submitTime).getHours() : '0' + String(new Date(submitTime).getHours()), //小时 
                "m": new Date(submitTime).getMinutes() >= 10 ? new Date(submitTime).getMinutes() : '0' + String(new Date(submitTime).getMinutes()), //分 
                "s": new Date(submitTime).getSeconds() >= 10 ? new Date(submitTime).getSeconds() : '0' + String(new Date(submitTime).getSeconds()), //秒 
            };
            console.log(o)
            data.data.orderHead.submitTime = o.d + "/" + o.M + "/" + o.y + " " + o.h + ":" + o.m
            var startTime = data.data.orderHead.startTimeStr;
            var ssdat = new Date(startTime.substring(0, 4), parseInt(startTime.substring(5, 7)) - 1, startTime.substring(8, 10))
            var stateMonth = Format.getMonth(parseInt(startTime.substring(5, 7)), that.data.isChinese),
                stateDay = parseInt(startTime.substring(8, 10)) + (that.data.isChinese ? '日 ' : ' '),
                stateWeek = Format.getWeek(ssdat.getDay(), that.data.isChinese),
                stateHours = (ssdat.getHours() > 12 ? 24 - ssdat.getHours() : ssdat.getHours() == 0 ? 12 : ssdat.getHours()) + (startTime.substring(13, 16) + (ssdat.getHours() >= 12 ? "pm" : "am"));
            data.data.orderHead.startTimeStr = stateMonth + stateDay + stateWeek + " " + stateHours
            var endTime = data.data.orderHead.endTimeStr;
            var endat = new Date(endTime.substring(0, 4), parseInt(endTime.substring(5, 7)) - 1, endTime.substring(8, 10))
            var endMonth = Format.getMonth(parseInt(endTime.substring(5, 7)), that.data.isChinese),
                endDay = parseInt(endTime.substring(8, 10)) + (that.data.isChinese ? '日 ' : ' '),
                endWeek = Format.getWeek(endat.getDay(), that.data.isChinese),
                endHours = (endat.getHours() > 12 ? 24 - endat.getHours() : endat.getHours() == 0 ? 12 : endat.getHours()) + (endTime.substring(13, 16) + (endat.getHours() >= 12 ? "pm" : "am"));
            data.data.orderHead.endTimeStr = endMonth + endDay + endWeek + " " + endHours

            if ((data.data.orderHead.eventEndTime - data.data.orderHead.submitTime) / 86400000 >= 1) {
                data.data.orderHead.endTimeStr = endTime.substring(0, 4) + (that.data.isChinese ? '年 ' : ' ') + endMonth + endDay + endWeek + " " + endHours
            } else {
                data.data.orderHead.endTimeStr = endHours
            }
            var newTime = new Date().getTime()
            var sayTime = data.data.orderHead.promoteTime //喊话时间
            var promoteTime
            if ((((sayTime - newTime)) / 86400000 > 7)) { //剩余时间大于一天
                promoteTime = this.data.isChinese ? +"7天前" : "7 days Ago"
            } else if ((((sayTime - newTime)) / 86400000 < 7) && (((sayTime - newTime)) / 86400000 > 2)) {
                promoteTime = this.data.isChinese ? "一周内" : "Week"
            } else if ((((sayTime - newTime)) / 86400000 < 2) && (((sayTime - newTime)) / 86400000 > 1)) {
                promoteTime = this.data.isChinese ? "昨天" : "Yesterday"
            } else {
                promoteTime = this.data.isChinese ? "今天" : "Today"
            }
            that.setData({
                promoteTime: promoteTime
            })
            that.setData({
                items: data.data.orderHead,
                loadMore: false
            })
        })
    },
    close() {
        this.setData({
            codeShow: false
        })
    },
    copy(e) {
        wx.setClipboardData({
            data: this.data.items.number,
            success: function(res) {
                wx.getClipboardData({
                    success: function(res) {
                        console.log(res)
                    },
                    fail(res) {
                        console.log(res)
                    }
                })
            }
        })
    },
    setCanvasSize: function() {
        var size = {};
        try {
            var res = wx.getSystemInfoSync();
            var scale = 750 / 686; //不同屏幕下canvas的适配比例；设计稿是750宽
            var width = res.windowWidth / scale / 2;
            var height = width; //canvas画布为正方形
            size.w = width;
            size.h = height;
        } catch (e) {
            // Do something when catch error

        }
        return size;
    },
    bindchange(e) {
        this.createQrCode(this.data.codeList[e.detail.current].number, "mycanvas" + e.detail.current, this.data.size.w, this.data.size.h);
    },
    createQrCode: function(url, canvasId, cavW, cavH) {
        //调用插件中的draw方法，绘制二维码图片
        var that = this
        QR.qrApi.draw(url, canvasId, cavW, cavH);
        setTimeout(function() {
            wx.canvasToTempFilePath({
                width: 350,
                height: 350,
                destWidth: 350,
                destHeight: 350,
                canvasId: canvasId,
                success: function(res) {
                    that.setData({
                        opgCode: res.tempFilePath
                    })
                },
                fail(res) {}
            })
        }, 300)
    },
    Count() {
        var totalCount = this.data.totalCount;
        // var totalCount = 8;
        var newCountList = []
        for (let j = 1; j < totalCount + 1; j++) {
            newCountList.push(j)
        }
        var a_len = newCountList.length;
        var result = [];
        for (var i = 0; i < a_len; i += 5) {
            result.push(newCountList.slice(i, i + 5));
        }
        var newArr = []
        for (let a = 0; a < result.length; a++) {
            if (result[a].length == 1) {
                newArr.push(result[a][0])
            } else {
                newArr.push(result[a][0] + "-" + result[a][result[a].length - 1])
            }
        }
        this.setData({
            countArr: newArr
        })
    },

    nav(e) {
        var that = this
        that.setData({
            navIndex: e.currentTarget.dataset.index,
            pageNumber: 1,
            loadMore: false,
            items: [],
            hidden: false,
            isAll: false
        })
        getTicket(that)

    },
    footerC(e) {
        this.setData({
            ftIndex: e.currentTarget.dataset.index + 1,
            codeList: [],
            current: 0,
        })
        getTicketList(this, this.data.lookEventId, this.data.lookEventType)
    },

    look(e) {
        var that = this
        that.setData({
            codeShow: true,
            codeList: [],
            ftIndex: 1,
            current: 0,
            lookEventId: e.currentTarget.dataset.id,
            lookEventType: that.data.items.orderLineList[0].objectType
        })

        getTicketList(that, e.currentTarget.dataset.id, that.data.items.orderLineList[0].objectType)
    },

    call(e) {
        wx.makePhoneCall({
            phoneNumber: e.currentTarget.dataset.phone //仅为示例，并非真实的电话号码
        })
    },
    again(e) {
        let id = e.currentTarget.dataset.id
        wx.navigateTo({
            url: '../activityDetails/activityDetails?id=' + id,
            success: function(res) {},
            fail: function(res) {},
            complete: function(res) {},
        })
    },
    thirClick(e) { //点击第三方票券
        clickCount++
        if (clickCount == 3) {
            this.setData({
                thirdparty: false
            })
            clickCount = 0
        }
        this.createQrCode(e.currentTarget.dataset.number, "mycanvas" + e.currentTarget.dataset.index, this.data.size.w, this.data.size.h);
    },
    opgClick(e) { //点击opg票券
        // if()
        this.setData({
            thirdparty: true
        })
        this.createQrCode(e.currentTarget.dataset.number, "mycanvas" + e.currentTarget.dataset.index, this.data.size.w, this.data.size.h);
    }
})